package com.kangfu.wechat.api;


import com.kangfu.common.exception.BusinessException;
import com.kangfu.wechat.bean.request.GetPhoneRequest;
import com.kangfu.wechat.bean.result.Phone;
import com.kangfu.wechat.bean.result.Token;
import com.kangfu.wechat.utils.JsonUtil;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserApi extends BaseApi {

    private static final Logger logger = LoggerFactory.getLogger(TokenApi.class);


    public static Phone getUserPhone(String appid, String secret, String code) {
        Token token = TokenApi.getToken(appid, secret);
        String url = BaseApi.BASE_URI + "/wxa/business/getuserphonenumber?access_token=" + token.getAccess_token();

        //构建请求body
        GetPhoneRequest getPhoneRequest = new GetPhoneRequest();
        getPhoneRequest.setCode(code);
        String jsonStr = JsonUtil.toJSONString(getPhoneRequest);
        RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), jsonStr);

        OkHttpClient okHttpClient = new OkHttpClient(); // 创建OkHttpClient对象
        Request request = new Request.Builder().url(url).post(body).build();
        try{
            Response response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) { // 判断是否成功
                String string = response.body().string();
                logger.info("getuserinfo response: " + string);
                Phone phone = JsonUtil.parseObject(string, Phone.class);
                if (phone == null) {
                    throw new BusinessException("获取用户手机号 失败");
                }
                return phone;
            } else {
                logger.error("获取用户手机号 失败 : code : " + response.code() + " || message : " + response.message());
                throw new BusinessException("获取用户手机号 失败");
            }
        } catch (Exception e){
            logger.error("获取用户手机号 失败 : " + e.getMessage());
            throw new BusinessException("获取用户手机号 失败");
        }
    }

}
